﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.ReceptionGoods
{	public partial class SupplierReturn : Form
	{	private	Util.ActionType actionType;
		private	SupplierReturns supplierReturns;
//-------------------------------------------------------------------------------------------------
		private	DIProject.DataSets.waybillsData supplierReturnsWaybillsData{get{return supplierReturns != null? supplierReturns.waybillsData: null;}}
		private	DIProject.DataSets.waybillsDataTableAdapters.SupplierReturnsTableAdapter supplierReturnsTableAdapter{get{return supplierReturns != null? supplierReturns.supplierReturnsTableAdapter: null;}}
		private	DIProject.DataSets.waybillsData.SupplierReturnsRow supplierReturnsRow = null;
		private	int docId{get{return supplierReturnsRow != null? supplierReturnsRow.Id: 0;}}
		private	string docNumber{get{return supplierReturnsRow != null? supplierReturnsRow.DocNumber: Properties.Resources.strUndefined;}}
		private	string docDate{get{return supplierReturnsRow != null? supplierReturnsRow.DocDate.ToString("d"): Properties.Resources.strUndefined;}}
		private decimal sum
		{	get
			{	object s = waybillsData.SupplierReturnLines.Compute("sum(RetailSum)", null);
				return s is decimal? (decimal)s: 0m;
			}
		}
		private int supplierId{get{return comboBoxSupplier.SelectedValue is int? (int)comboBoxSupplier.SelectedValue: 0;}}
		private int? supplierDocId = null;
//-------------------------------------------------------------------------------------------------
		public SupplierReturn()
		{
		}

		public SupplierReturn(Util.ActionType actionType, SupplierReturns supplierReturns)
		{	InitializeComponent();
			textFormat = Text;
			this.actionType		= actionType;
			this.supplierReturns= supplierReturns;
			toolStripButtonUpdate.Enabled = false;
			toolStripButtonDelete.Enabled = false;
			if(	actionType == DIProject.Util.ActionType.Update
			&&	supplierReturns != null
			&&	supplierReturns.supplierReturnsGridView.CurrentCell != null)
				supplierReturnsRow = (DIProject.DataSets.waybillsData.SupplierReturnsRow)((DataRowView)supplierReturns.supplierReturnsGridView.CurrentCell.OwningRow.DataBoundItem).Row;
		}
//-------------------------------------------------------------------------------------------------
		private readonly string textFormat;
		private void SetCaption()
		{	Text = string.Format
			(	textFormat
			,	docNumber
			,	docDate
			,	sum.ToString("N2")
			);
		}
//-------------------------------------------------------------------------------------------------
		private void SupplierReturn_Load(object sender, EventArgs e)
		{	try
			{	contragentsTableAdapter.Fill(dictionary.Contragents);
				switch(actionType)
				{	case DIProject.Util.ActionType.Insert:
						supplierReturnsRow = supplierReturnsWaybillsData.SupplierReturns.NewSupplierReturnsRow();
						supplierReturnsRow.DocDate	= DateTime.Today;
						supplierReturnsRow.MD		= DateTime.Now;
						supplierReturnsRow.MW		= FirstForm.Login;
						supplierReturnsWaybillsData.SupplierReturns.AddSupplierReturnsRow(supplierReturnsRow);
						goto case DIProject.Util.ActionType.Update;
					case DIProject.Util.ActionType.Update:
						supplierReturnLinesTableAdapter.Fill(waybillsData.SupplierReturnLines, docId);
						comboBoxSupplier.DataBindings.Add("SelectedValue", supplierReturnsRow, "SupplierId");
						textBoxNote.DataBindings.Add("Text", supplierReturnsRow, "Note");
						comboBoxSupplier.Enabled = waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.CurrentRows).Length == 0;
						object suppDocId = waybillsData.SupplierReturnLines.Compute("min(SupplierDocId)", null);
						if(suppDocId is int)
							supplierDocId = (int)suppDocId;
						break;
				}
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			SetCaption();
		}
//-------------------------------------------------------------------------------------------------
		private void SupplierReturn_FormClosing(object sender, FormClosingEventArgs e)
		{	BindingManagerBase bindingManager = BindingContext[supplierReturnsRow];
			if(bindingManager != null)
				bindingManager.EndCurrentEdit();
			int		delLines = waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.Deleted	).Length
				,	insLines = waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.Added	).Length
				;
			if(supplierReturnsRow.RowState != DataRowState.Unchanged
			|| delLines > 0
			|| insLines > 0)
				switch(MessageBox.Show
					(	this
					,	Properties.Resources.strDocIsChanged
					,	Properties.Resources.strConfirmation
					,	MessageBoxButtons.YesNoCancel
					,	MessageBoxIcon.Question
					,	MessageBoxDefaultButton.Button1
					)
				)
				{	case DialogResult.Yes:
						toolStripButtonSave_Click(toolStripButtonSave, EventArgs.Empty);
						delLines = waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.Deleted	).Length;
						insLines = waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.Added	).Length;
						if(supplierReturnsRow.RowState != DataRowState.Unchanged
						|| delLines > 0
						|| insLines > 0)
							e.Cancel = true;
						break;
					case DialogResult.No:
						supplierReturnsRow.RejectChanges();
						waybillsData.SupplierReturnLines.RejectChanges();
						break;
					case DialogResult.Cancel:
						e.Cancel = true;
						break;
				}
		}
		//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void SupplierReturn_Resize(object sender, EventArgs e)
		{	int width = panelHeader.ClientSize.Width - labelSupplier.Left - comboBoxSupplier.Left;
			comboBoxSupplier.	Width = width;
			textBoxNote.		Width = width;
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
		{	if(clickedCell != null)
			{	updateToolStripMenuItem.Enabled = true;
				deleteToolStripMenuItem.Enabled = true;
			}
			else
			{	updateToolStripMenuItem.Enabled = false;
				deleteToolStripMenuItem.Enabled = false;
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private DataGridViewCell clickedCell = null;
		private void linesGridView_MouseDown(object sender, MouseEventArgs e)
		{	clickedCell = null;
			if(e.Button == MouseButtons.Right)
			{	DataGridView.HitTestInfo hit = linesGridView.HitTest(e.X, e.Y);
				if(hit.Type == DataGridViewHitTestType.Cell)
					linesGridView.CurrentCell = clickedCell = linesGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
			}
		}
//-------------------------------------------------------------------------------------------------
		private void linesGridView_CurrentCellChanged(object sender, EventArgs e)
		{	if(linesGridView.CurrentCell != null)
			{	toolStripButtonUpdate.Enabled = true;
				toolStripButtonDelete.Enabled = true;
			}
			else
			{	toolStripButtonUpdate.Enabled = false;
				toolStripButtonDelete.Enabled = false;
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void toolStripRefresh_Click(object sender, EventArgs e)
		{	try
			{	supplierReturnLinesTableAdapter.Fill(waybillsData.SupplierReturnLines, docId);
				comboBoxSupplier.Enabled = waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.CurrentRows).Length == 0;
				int? suppDocId = (int?)waybillsData.SupplierReturnLines.Compute("min(SupplierDocId)", null);
				if(suppDocId != null)
					supplierDocId = suppDocId;
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			SetCaption();
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripButtonSave_Click(object sender, EventArgs e)
		{	try
			{	BindingManagerBase bindingManager = BindingContext[supplierReturnsRow];
				if(bindingManager != null)
					bindingManager.EndCurrentEdit();
				int		delLines = waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.Deleted	).Length
					,	insLines = waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.Added	).Length
					;
				supplierReturnsTableAdapter.Update(supplierReturnsRow);						// Заголовок документа
				if(actionType == DIProject.Util.ActionType.Insert)
				{	supplierReturns.supplierReturnsGridView.CurrentCell = supplierReturns.supplierReturnsGridView.Rows[supplierReturns.supplierReturnsGridView.Rows.Count - 1].Cells[supplierReturns.supplierReturnsGridView.CurrentCell.ColumnIndex];
					for(int i = 0, n = waybillsData.SupplierReturnLines.Rows.Count; i < n; ++i)
						waybillsData.SupplierReturnLines[i].DocId = supplierReturnsRow.Id;
				}
				supplierReturnLinesTableAdapter.Update(waybillsData.SupplierReturnLines);	// Строки документа
				supplierReturnsRow.SupplierName	= comboBoxSupplier.Text;
				supplierReturnsRow.Lines		= supplierReturnsRow.Lines - delLines + insLines;
				supplierReturnsRow.DocSum		= sum;

				supplierReturnsRow.AcceptChanges();
				waybillsData.SupplierReturnLines.AcceptChanges();
			}
			catch(SqlException eq)
			{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			catch(Exception ex)
			{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripPrint_Click(object sender, EventArgs e)
		{	BindingManagerBase bindingManager = BindingContext[supplierReturnsRow];
			if(bindingManager != null)
				bindingManager.EndCurrentEdit();
			bool changed=	supplierReturnsRow.RowState != DataRowState.Unchanged
						||	waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.Deleted).Length > 0
						||	waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.Added	).Length > 0
					//?	||	DIProject.Util.Common.HasChanges(waybillsData.SupplierReturnLines)
						;
			if(changed)
			{	if(MessageBox.Show
				(	this
				,	Properties.Resources.strDocIsChanged
				,	Properties.Resources.strConfirmation
				,	MessageBoxButtons.YesNo
				,	MessageBoxIcon.Question
				,	MessageBoxDefaultButton.Button1
				) == DialogResult.Yes)
				{	try
					{	
						toolStripButtonSave_Click(toolStripButtonSave, EventArgs.Empty);
						changed =	supplierReturnsRow.RowState != DataRowState.Unchanged
								||	waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.Deleted).Length > 0
								||	waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.Added	).Length > 0
								;
					}
					catch(SqlException eq)
					{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
					catch(Exception ex)
					{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
				}
			}
			if(!changed)
			{	DIProject.Reports.ChoiceReport choiceReport = new DIProject.Reports.ChoiceReport();
				choiceReport.ReportsGridView.Rows.Add(0, "Акт возврата");
				choiceReport.ReportsGridView.Rows.Add(1, "Накладная ТОРГ-12");
				if(choiceReport.ShowDialog(this) == DialogResult.OK
				&& choiceReport.ReportsGridView.CurrentCell != null)
				{	switch(choiceReport.ReportsGridView.CurrentCell.RowIndex)
					{	case 0:		// Акт возврата
							{	SupplierReturnRpt0 supplierReturnRpt0 = new SupplierReturnRpt0(docId);
								supplierReturnRpt0.ShowDialog(this);
							}
							break;
						case 1:		// Накладная ТОРГ-12
							{	SupplierReturnRpt1 supplierReturnRpt1 = new SupplierReturnRpt1(docId);
								supplierReturnRpt1.ShowDialog(this);
							}
							break;
					}
				}
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripInsert_Click(object sender, EventArgs e)
		{	SupplierReturnLine supplierReturnLine = new SupplierReturnLine(Util.ActionType.Insert, supplierId, supplierDocId);
			if(supplierReturnLine.ShowDialog(this) == DialogResult.OK)
			{	try
				{	DIProject.DataSets.waybillsData.SupplierReturnPartiesRow partyRow = supplierReturnLine.PartyRow;
					DIProject.DataSets.waybillsData.SupplierReturnLinesRow newRow = waybillsData.SupplierReturnLines.NewSupplierReturnLinesRow();
					newRow.DocId			= docId;
					newRow.PartyId			= partyRow.Id;
					newRow.Name				= partyRow.Name;
					newRow.ManufacturerId	= partyRow.ManufacturerId;
					newRow.ManufacturerName	= partyRow.ManufacturerName;
					newRow.RetailPrice		= partyRow.RetailPrice;
					newRow.Qntty			= supplierReturnLine.Qntty;
					newRow.RetailSum		= partyRow.RetailPrice*supplierReturnLine.Qntty;
					newRow.SupplierDocId	= partyRow.SupplierDocId;
				//?	newRow.ReturnLineId		= ;
					newRow.Note				= supplierReturnLine.Note;
					newRow.MD				= DateTime.Now;
					newRow.MW				= FirstForm.Login;
					if(waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.CurrentRows).Length == 0)
						supplierDocId = partyRow.SupplierDocId;
					waybillsData.SupplierReturnLines.AddSupplierReturnLinesRow(newRow);
					comboBoxSupplier.Enabled = waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.CurrentRows).Length == 0;
					linesGridView.CurrentCell = linesGridView.Rows[linesGridView.Rows.Count - 1].Cells[linesGridView.CurrentCell.ColumnIndex];
				}
				catch(SqlException eq)
				{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				SetCaption();
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripUpdate_Click(object sender, EventArgs e)
		{	if(linesGridView.CurrentCell != null)
			{	try
				{	DIProject.DataSets.waybillsData.SupplierReturnLinesRow row = (DIProject.DataSets.waybillsData.SupplierReturnLinesRow)((DataRowView)linesGridView.CurrentCell.OwningRow.DataBoundItem).Row;
					SupplierReturnLine supplierReturnLine	= new SupplierReturnLine(Util.ActionType.Update, supplierId, supplierDocId);
					supplierReturnLine.Party		= row.PartyId;
					supplierReturnLine.Manufacturer	= row.ManufacturerName;
					supplierReturnLine.Qntty		= row.Qntty;
					supplierReturnLine.Price		= row.RetailPrice;
					supplierReturnLine.Note			= row.Note;
					if(supplierReturnLine.ShowDialog(this) == DialogResult.OK)
					{	row.Qntty			= supplierReturnLine.Qntty;					// Меняются только количество
						row.RetailSum		= row.RetailPrice*supplierReturnLine.Qntty;	//   сумма
						row.Note			= supplierReturnLine.Note;					//   и примечание
						SetCaption();
					}
				}
				catch(SqlException eq)
				{	MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
//-------------------------------------------------------------------------------------------------
		private void toolStripDelete_Click(object sender, EventArgs e)
		{	DIProject.DataSets.waybillsData.SupplierReturnLinesRow rowToDelete;
			if(	linesGridView.CurrentCell != null
			&&	(rowToDelete = (DIProject.DataSets.waybillsData.SupplierReturnLinesRow)((DataRowView)linesGridView.CurrentCell.OwningRow.DataBoundItem).Row) != null
			&&	MessageBox.Show
				(	this
				,	string.Format(Properties.Resources.strDeleteDocLine, rowToDelete.Name)
				,	Properties.Resources.strConfirmation
				,	MessageBoxButtons.YesNo
				,	MessageBoxIcon.Question
				,	MessageBoxDefaultButton.Button1
				) == DialogResult.Yes
			)
			{	try
				{	rowToDelete.Delete();
					if(waybillsData.SupplierReturnLines.Select(null, null, DataViewRowState.CurrentRows).Length == 0)
					{	supplierDocId = null;
						comboBoxSupplier.Enabled = true;
					}
					else
						comboBoxSupplier.Enabled = false;
				}
				catch(SqlException eq)
				{	rowToDelete.RejectChanges();
					MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	rowToDelete.RejectChanges();
					MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				SetCaption();
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
		private void linesGridView_KeyDown(object sender, KeyEventArgs e)
		{	if(e.KeyCode == Keys.Enter)
				e.Handled = true;
		}
//-------------------------------------------------------------------------------------------------
		private void linesGridView_KeyPress(object sender, KeyPressEventArgs e)
		{	if(e.KeyChar == '\r' && linesGridView.CurrentCell != null)
				toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
		}
//-------------------------------------------------------------------------------------------------
		private void linesGridView_MouseDoubleClick(object sender, MouseEventArgs e)
		{	DataGridView.HitTestInfo hit = linesGridView.HitTest(e.X, e.Y);
			if(hit.Type == DataGridViewHitTestType.Cell)
			{	linesGridView.CurrentCell = clickedCell = linesGridView.Rows[hit.RowIndex].Cells[hit.ColumnIndex];
				toolStripUpdate_Click(toolStripButtonUpdate, EventArgs.Empty);
			}
		}
//-------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------
	}
}